package toy.keli.edic.ui.home.homescreen

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import toy.keli.edic.data.PreviewData
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.config.MenuConf
import toy.keli.edic.data.model.Book
import toy.keli.edic.data.model.Category
import toy.keli.edic.domain.model.WordModel
import toy.keli.edic.ui.bookmark.BookMarkEvent
import toy.keli.edic.ui.history.HistoryViewModel
import toy.keli.edic.ui.history.HistoryWords
import toy.keli.edic.ui.history.components.HistroyFilter
import toy.keli.edic.ui.home.HomeEvents
import toy.keli.edic.ui.home.nowChapters
import toy.keli.edic.ui.home.wGroups
import toy.keli.edic.ui.listenbook.ListenBookData
import toy.keli.edic.ui.main.components.Display.mt
import toy.keli.edic.ui.main.components.FlowRow
import toy.keli.edic.ui.main.components.InputDialog
import toy.keli.edic.ui.main.components.LimitedFlowRow
import toy.keli.edic.ui.main.components.ViewButton
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.view.MPopMenu

@Composable
@Preview(showBackground = true)
fun GroupTools(){
    if( LocalInspectionMode.current) {
       PreviewData.groupTools();
    }

    Column(
        modifier = Modifier
            .alpha(0.9f)
            .background(MaterialTheme.colorScheme.background)
            .fillMaxWidth()
            .padding(10.dp,10.dp,0.dp,bottom = 0.dp)
            .pointerInput(Unit) {
                HomeEvents.timeOutClosedDownMenu = false;
            }
    ) {
        BookNavInfo() {
            //章节的切换
            if (nowChapters.isNotEmpty()) {
                treeItem(nowChapters, wGroups) {
                    HomeEvents.GroupInfoPage.onChapterClick(it)
                }
            }
        }
        if(BookConf.words.size==0) return;
        Divider(
            modifier = Modifier.padding(vertical = 8.dp),
            color = Color.LightGray, // 分割线颜色
            thickness = 1.dp, // 分割线厚度
        )
        LazyColumn(
            state = rememberLazyListState(),
            modifier = Modifier.padding(10.dp)
        ) {
            items(1) {
                wordList()
            }
        }

        Divider(
            modifier = Modifier.padding(vertical = 8.dp),
            color = Color.LightGray, // 分割线颜色
            thickness = 1.dp, // 分割线厚度
        )

    }
}
@Composable
fun BookNavInfo(canCategoryChange:Boolean=false, canArticleChange:Boolean=false, child: @Composable ()->Unit={}){
    val pid = BookConf.instance.pid()
    val paths = Category.getParents(pid);
    var bName by remember { mutableStateOf(Book.name()) }
    var aList:List<BookConf>? by remember { mutableStateOf(null) }
    if(paths.size==0 && bName.isEmpty()) return;
    if(canArticleChange){
        LaunchedEffect(pid){
            Book.getHaveBooks {
                aList = it
            }
        }
    }
    FlowRow (modifier = Modifier

    ){
        Text(mt("路径")+": ", modifier = Modifier.padding(end = 10.dp))
        //目录的切换
        paths.forEach { path ->
            treeItem(path.name, onLongClick = {
                HomeEvents.onBookShow(path.id)
            }) {
                HomeEvents.onBookShow(path.pid,categoryId=path.id)
            }
        }
        if(bName.isNotEmpty()) {
            //书本的切换
            treeItem(bName,aList?.map{it.name},
                onClick =  {selected->
                    if(canArticleChange){
                        aList?.find{ it.name == selected}?.let {
                            bName = it.name
                            ListenBookData.instance.changeBook(it)
                        }
                    }else {
                        HomeEvents.onBookShow(pid,articleId=BookConf.instance.id)
                    }
                },
                onLongClick = {
                    HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.showArticle)
                }
            )
        }
        child()
    }
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun treeItem(name:String,items:List<String>?=null,onLongClick:()->Unit={},onClick:(name:String)->Unit){
    Text("/", color = Color.Gray, fontSize = 11.sp, modifier = Modifier.padding(3.dp))
    Column {
        var menu: MPopMenu? =null;
        if(items!=null){
            menu = MPopMenu.Unspecified
            menu.add()
        }
        Text(mt(name), color = Color.Blue, modifier = Modifier
          .combinedClickable(
            onClick={
                if (menu != null) {
                    menu.show(items = items) { k, v ->
                        onClick(k)
                    }
                } else {
                    onClick(name)
                }
            },
            onLongClick = {
                onLongClick()
            }
          )
        )
    }
}
@Composable
fun wordList(){
    if(! LocalInspectionMode.current) {
        InputDialog.add("AddArticle","SaveToFile",{
            BookMarkEvent.onAdd(it, 0)
            ActivityRun.msg("Saved")
        })
        val historyViewModel: HistoryViewModel = hiltViewModel()
        HistroyFilter.add(
            historyViewModel, listOf(
                HistroyFilter.types.type,
                HistroyFilter.types.level
            )
        )
    }
    if(BookConf.words.size>0) {
        val menu = MPopMenu(listOf(
            MPopMenu.dataClass("Copy"),
            MPopMenu.dataClass("export"),
            MPopMenu.dataClass("Save"),
            MPopMenu.dataClass("SaveAll"),
            MPopMenu.dataClass("过滤"),
//                    MPopMenu.dataClass("exportAndOpen"),
//                    MPopMenu.dataClass("exportAndJumpTo")
        )).upMtTitle()
        Row {
            Title("WordList") {
                HomeEvents.GroupInfoPage.onFunsClick(menu)
            }
            menu.add()
            ViewButton("findGame"){
                HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.findGame)
            }
            ViewButton("jdc_select"){
                HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.jdc_select)
            }
            ViewButton("jdc_write"){
                HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.jdc_write)
            }
        }
    }
    val sWord = remember {  mutableStateOf(BookConf.instance.word) }
    // 记录是否需要显示省略提示
    LimitedFlowRow(items = BookConf.words,maxLines = 3) {
//                val tColor = if(it.isStudyed)  Color.Red else MaterialTheme.colors.primary
            val tColor = if (it.word == sWord.value) Color.Red else MaterialTheme.colorScheme.primary
            Text(text = it.word, color = tColor,
                fontSize = 14.sp,
                modifier = Modifier
                    .padding(horizontal = 5.dp)
                    .clickable {
                        sWord.value = it.word;
                        HomeEvents.GroupInfoPage.onWordClick(it)
                    }
            )
    }
}
@Composable
fun chapterList(){
    val name = BookConf.instance.name
    Row {
        Title(name.replace(Regex("\\.\\w+$"), "")) {
            val pid = Book.cid()
            BookMarkEvent.bookId = BookConf.instance.id
//                    NavScreen.BookmarkScreen.open("?pid=${pid}")
            HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.showCategory)
        }
        ViewButton("listenBook"){
            HomeEvents.SwitchMainPage.onItemClick(MenuConf.mode.showArticle)
        }
    }
    if (wGroups.size > 0) {
        FlowRow {
            wGroups.forEach {
                val tColor =
                    if (it.equals(nowChapters)) Color.Red else MaterialTheme.colorScheme.primary
                Text(text = mt(it), color = tColor, fontSize = 14.sp, modifier = Modifier
                    .padding(10.dp)
                    .clickable { HomeEvents.GroupInfoPage.onChapterClick(it) }
                )
            }
        }
    }
}

@Composable
fun HistoryWordsShow() {
//    Title(mt("WordHistory"))
    FlowRow {
        HistoryWords.menu.items.reversed().forEach {
            Text(text = it.title,
                fontSize = 14.sp,
                modifier = Modifier
                    .padding(10.dp)
                    .clickable {
                        HistoryWords.slice(it.index)
                        HomeEvents.GroupInfoPage.onHistoryWordClick(it.value as WordModel)
                    }
            )
        }
        HistoryWords.sliceDiscard.reversed().forEach {
            Text(text = it.word, color = Color.Gray,
                fontSize = 14.sp,
                modifier = Modifier
                    .padding(10.dp)
                    .clickable {
                        HomeEvents.GroupInfoPage.onHistoryWordClick(it)
                    }
            )
        }
    }
}
